Page({
  data: {
    merchantId: "",
    dishes: [],
    status: 1, // 1-上架，0-下架
    page: 1,
    pageSize: 10,
    total: 0,
    loading: false,
    hasMore: true,
  },

  onLoad(options) {
    if (options.merchantId) {
      this.setData({
        merchantId: options.merchantId,
      });
      this.loadDishes();
    }
  },

  // 加载菜品列表
  async loadDishes(isLoadMore = false) {
    if (this.data.loading || (!isLoadMore && !this.data.hasMore)) return;

    this.setData({ loading: true });

    try {
      const { result } = await wx.cloud.callFunction({
        name: "getMerchantDishes",
        data: {
          merchantId: this.data.merchantId,
          status: this.data.status,
          page: isLoadMore ? this.data.page + 1 : 1,
          pageSize: this.data.pageSize,
        },
      });

      if (result.code === 0) {
        const { list, total } = result.data;
        this.setData({
          dishes: isLoadMore ? [...this.data.dishes, ...list] : list,
          total,
          page: isLoadMore ? this.data.page + 1 : 1,
          hasMore: list.length === this.data.pageSize,
          loading: false,
        });
      } else {
        wx.showToast({
          title: result.msg || "加载失败",
          icon: "none",
        });
        this.setData({ loading: false });
      }
    } catch (err) {
      console.error("加载菜品列表失败：", err);
      wx.showToast({
        title: "加载失败",
        icon: "none",
      });
      this.setData({ loading: false });
    }
  },

  // 切换菜品状态
  async handleStatusChange(e) {
    const { dishId, status } = e.currentTarget.dataset;
    const newStatus = status === 1 ? 0 : 1;

    try {
      const { result } = await wx.cloud.callFunction({
        name: "updateDishStatus",
        data: {
          dishId,
          status: newStatus,
        },
      });

      if (result.code === 0) {
        wx.showToast({
          title: "更新成功",
          icon: "success",
        });
        // 重新加载列表
        this.loadDishes();
      } else {
        wx.showToast({
          title: result.msg || "更新失败",
          icon: "none",
        });
      }
    } catch (err) {
      console.error("更新菜品状态失败：", err);
      wx.showToast({
        title: "更新失败",
        icon: "none",
      });
    }
  },

  // 切换状态标签
  handleTabChange(e) {
    const status = e.currentTarget.dataset.status;
    if (status === this.data.status) return;

    this.setData({
      status,
      page: 1,
      hasMore: true,
    });
    this.loadDishes();
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.setData({
      page: 1,
      hasMore: true,
    });
    this.loadDishes().then(() => {
      wx.stopPullDownRefresh();
    });
  },

  // 上拉加载更多
  onReachBottom() {
    if (this.data.hasMore) {
      this.loadDishes(true);
    }
  },
});
